package com.atguigu.test.mvc.my;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zp
 * @version 1.0
 * @description: 自定义的beanName匹配器
 * @date 2023/1/27 15:59
 */
public class MyBeanNameUrlHandlerMapping implements HandlerMapping, InitializingBean, ApplicationContextAware {
    private ApplicationContext applicationContext;
    private Map<String, Controller> collect;
    /**
     * @description: 处理方法 组成链
     * @author zp
     * @date: 2023/1/27 16:16
     * @param request
     * @return HandlerExecutionChain
     */
    @Override
    public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
        String key = request.getRequestURI();
        Controller controller = collect.get(key);
        if(controller!=null){
            return new HandlerExecutionChain(controller);
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, Controller> beansOfType = applicationContext.getBeansOfType(Controller.class);
        collect = beansOfType.entrySet().stream().filter(e -> e.getKey().startsWith("/")).
                collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
        System.out.println(collect);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
